import { createSlice } from '@reduxjs/toolkit'

let Countslice = createSlice({
    name: 'Countslice',
    initialState: {
        list: []
    },
    reducers: {
        addList: (state, action) => {
            let copy = [...state.list]
            let index = copy.findIndex(item => item._id === action.payload._id)
            if (index === -1) {
                action.payload.num = 1
                action.payload.state = false
                state.list.push(action.payload)
                return state
            } else {
                copy[index].num += 1
                state.list = copy
                return state
            }

        },
        addNum: (state, action) => {
            let copy = [...state.list]
            console.log(action.payload)
            let item = copy.find(item => item._id == action.payload)
            item.num++
            state.list = copy
            return state
        },
        jianNum: (state, action) => {
            let copy = [...state.list]
            console.log(action.payload)
            let item = copy.find(item => item._id == action.payload)
            item.num--
            state.list = copy
            return state
        },
        delItem: (state, action) => {
            let copy = [...state.list]
            console.log(action.payload)
            let index = copy.findIndex(item => item._id == action.payload)
            copy.splice(index, 1)
            state.list = copy
            return state
        }

    }
})

export let { addList, addNum, jianNum, delItem } = Countslice.actions

export default Countslice